import {
  createRouter,
  createWebHistory,
  createWebHashHistory,
} from "vue-router";

import "@/main.js";
import { useStore } from "@/store/index"; //引入store
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { adminList } from "./admin.js";
import { userList } from "./user.js";

NProgress.configure({
  easing: "ease", // 动画方式
  speed: 500, // 递增进度条的速度
  showSpinner: false, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3, // 初始化时的最小百分比,
});
const router = createRouter({
  routes: [
    {
      path: "/", //路由到的地址 (自定义)
      component: () => import("@/views/mainHome/index.vue"), //引入组件
      name: "Home", //组件名称
      meta: {
        title: "主页",
      },
      children: [...adminList, ...userList],
      redirect: () => {
        const store = useStore();
        return store.redirectPath || "/login"; // 根据需要设置默认的重定向路径
      },
    },
    {
      path: "/login",
      component: () => import("@/views/login/login.vue"),
      name: "Login",
      meta: {
        title: "登录页",
      },
    },
	{
	  path: "/adminLogin",
	  component: () => import("@/views/login/adminLogin.vue"),
	  name: "adminLogin",
	  meta: {
	    title: "后台登录页",
	  },
	},
    {
      path: "/403",
      component: () => import("@/views/error/403.vue"),
      name: "403",
      meta: {
        title: "403页面",
      },
    },
    {
      path: "/404",
      component: () => import("@/views/error/404.vue"),
      name: "404",
      meta: {
        title: "404页面",
      },
    },

    {
      path: "/:pathMatch(.*)",
      redirect: "/404",
    },
  ],
  history: createWebHistory("/lea/"), // 使用history模式
});

// 路由守卫拦截
router.beforeEach((to, from, next) => {
  NProgress.start();//这这里开启加载条
  window.document.title = to.meta.title;
  const store = useStore();
  const routerList = store.pathList;
  const token = store.token;
  //路由守卫
  if (to.matched.some((record) => record.meta.requireLogin)) {
	  //判断是否登录   //当前如果为登录页 或者token不存在 则需要跳转登录页
  	if (token) {
		let whiteList = ["/403", "/404", "/login","/adminLogin"]; //白名单
		if(routerList.length){
			// 判断是否有权限 如果没有权限 则跳转403 页面   // 403 404 页面不需要权限
			if (!routerList.includes(to.path) && !whiteList.includes(to.path)) {
				return next("/403");
			}
		}
  		next();
  	} else {
  		if (to.path.indexOf('login') > -1 || to.path == '/') {
  			next('/login');
  		}
  		if (to.path.indexOf('adminLogin') > -1) {
  			next('/adminLogin');
  		}
  	}
  } else {
  	next();
  }
});

router.afterEach(() => {
  NProgress.done();// 在即将进入新的页面组件前，关闭掉进度条
});
export default router;
